package com.mars.component.scheduler.utlis;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.quartz.QuartzJobBean;

import com.mars.common.spring.SpringContextHolder;
import com.mars.common.utils.ExceptionUtil;
import com.mars.common.utils.date.DateUtil;
import com.mars.component.scheduler.entity.SchedulerJob;
import com.mars.component.scheduler.entity.SchedulerJobLog;
import com.mars.component.scheduler.service.SchedulerJobLogService;

public class ScheduleJobQuartz extends QuartzJobBean {
	
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	private ExecutorService service = Executors.newSingleThreadExecutor(); 
	
	@Override
	protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
		SchedulerJob schedulerJob = (SchedulerJob) context.getMergedJobDataMap().get(SchedulerJob.JOB_PARAM_KEY);
		
		SchedulerJobLogService schedulerJobLogService = SpringContextHolder.getBean(SchedulerJobLogService.class) ;
		
		SchedulerJobLog log = new SchedulerJobLog() ;
		log.setJobId(schedulerJob.getJobId());
		log.setJobName(schedulerJob.getJobName());
		log.setJobGroup(schedulerJob.getJobGroup());
		log.setClassName(schedulerJob.getClassName());
		log.setBeanName(schedulerJob.getBeanName());
		log.setMethodName(schedulerJob.getMethodName());
		log.setParams(schedulerJob.getParams());
		log.setRemarks(schedulerJob.getRemarks());
		
		//作业开始时间
        long startTime = System.currentTimeMillis();
		
        try {
            //执行作业
        	logger.info("作业准备执行  ==>  作业名称：" + schedulerJob.getJobName() + "  作业ID：" + schedulerJob.getJobId() + "  分组名称：" + schedulerJob.getJobGroup() + "  Cron表达式：" + schedulerJob.getCronExpression());
        	
            ScheduleRunnable task = new ScheduleRunnable(
            		schedulerJob.getBeanName(), 
            		schedulerJob.getMethodName(), 
            		schedulerJob.getParams());
            
            Future<?> future = service.submit(task);
            
			future.get();
			
			//作业执行总时长
			long times = System.currentTimeMillis() - startTime;
			
			log.setStatus(0);
			log.setTimes((int)times);
			
			logger.info("作业执行完毕  ==>  作业名称：" + schedulerJob.getJobName() + "  作业ID：" + schedulerJob.getJobId() + "  分组名称：" + schedulerJob.getJobGroup() + "  Cron表达式：" + schedulerJob.getCronExpression() + "  时间：" + DateUtil.getCurrentDateTimeString() + "  总共耗时：" + times + "毫秒");
		} catch (Exception e) {
			//作业执行总时长
			long times = System.currentTimeMillis() - startTime;
			
			log.setStatus(1);
			log.setTimes((int)times);
			log.setError(ExceptionUtil.getStackTrace(e));
			
			logger.error("作业执行失败  ==>  作业名称：" + schedulerJob.getJobName() + "  作业ID：" + schedulerJob.getJobId() + "  分组名称：" + schedulerJob.getJobGroup() + "  Cron表达式：" + schedulerJob.getCronExpression() + "  时间：" + DateUtil.getCurrentDateTimeString() + "  总共耗时：" + times + "毫秒 ", e);
		} finally {
			//记录作业的执行信息到数据库
			schedulerJobLogService.insertSelective(log) ;
		}
	}

}
